<template>
	<div>
		<el-card style="max-width: 100%">
			<el-button
				type="primary"
				size="default"
				@click="editTrademark(null)"
				icon="plus"
				style="margin-bottom: 15px"
			>
				添加品牌
			</el-button>
			<el-table
				:data="page.records"
				:border="true"
				@selection-change="pageTrademark"
			>
				<el-table-column type="index" width="100" label="id" align="center" />
				<el-table-column label="品牌名称" prop="tmName" align="center" />
				<el-table-column label="品牌LOGO" prop="logoUrl" align="center">
					<template #default="{ row }">
						<img width="auto" height="100px" :src="row.logoUrl" />
					</template>
				</el-table-column>
				<el-table-column label="品牌操作" align="center">
					<template #default="{ row }">
						<el-button
							type="primary"
							size="small"
							icon="Edit"
							@click="editTrademark(row)"
						></el-button>
						<el-button
							type="primary"
							size="small"
							icon="Delete"
							@click="deleteTrademark(row.id)"
						></el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:current-page="page.current"
				v-model:page-size="page.size"
				:page-sizes="[5, 10, 20, 30]"
				:default-page-size="page.size"
				layout="prev,pager,next,jumper,->,sizes,total"
				:total="page.total"
				:page-count="page.pages"
				@size-change="pageSizeChange"
				@current-change="pageTrademark"
				style="margin-top: 15px"
			/>
		</el-card>

		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
			<el-form
				ref="formIns"
				:model="trademarkForm"
				label-width="80px"
				style="background-color: white"
				:rules="rules"
			>
				<el-form-item label="品牌名" prop="tmName">
					<el-input v-model="trademarkForm.tmName" />
				</el-form-item>
				<el-form-item label="品牌LOGO" style="height: 200px" prop="logoUrl">
					<el-upload
						class="avatar-uploader"
						action="/api/admin/product/fileUpload"
						:on-success="handleImgSuccess"
						:before-upload="beforeImgUpload"
						:show-file-list="false"
					>
						<img
							v-if="trademarkForm.logoUrl"
							:src="apiPrefix + trademarkForm.logoUrl"
							class="avatar"
						/>
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitTrademark"> 提交 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup name="Trademark">
	import { onMounted, ref, reactive } from 'vue';
	import type { FormInstance, FormRules } from 'element-plus';
	import {
		reqPageTrademark,
		reqSaveTrademark,
		reqUpdateTrademark,
		reqDeleteTrademark,
	} from '@/api/product/trademark';
	import type { PageType, ResponseType } from '@/api/common/type';
	import type { TrademarkType } from '@/api/product/trademark/type';
	// dialog是否显示
	let dialogVisible = ref(false);
	// dialog标题
	let dialogTitle = ref('');
	// 图片api前缀
	let apiPrefix = import.meta.env.VITE_APP_BASE_API_PREFIX;
	const jpgUrl = ref('');
	// 分页相关数据
	let page = reactive<PageType<TrademarkType>>({
		countId: null,
		current: 1,
		hitCount: true,
		maxLimit: null,
		optimizeCountSql: null,
		orders: [],
		pages: 1,
		records: [],
		searchCount: null,
		size: 5,
		total: 0,
	});
	// 品牌的form表单
	let formIns = ref<FormInstance>();
	let trademarkForm = reactive<TrademarkType>({
		id: undefined,
		tmName: '',
		logoUrl: '',
	});
	// form表单验证
	let rules = reactive<FormRules<TrademarkType>>({
		tmName: { required: true, message: '请输入品牌名', trigger: 'blur' },
		logoUrl: { required: true, message: '请上传品牌logo', trigger: 'blur' },
	});

	/**
	 * 分页请求品牌列表
	 */
	let pageTrademark = async () => {
		let { code, message, data } = await reqPageTrademark(
			page.current,
			page.size
		);
		if (code == 200) {
			Object.keys(data).forEach((key) => {
				(page as any)[key] = data[key];
			});
		} else {
			ElMessage.error({
				message: message,
			});
		}
	};
	/**
	 * 显示dialog编辑框，进行添加或者修改品牌
	 */
	let editTrademark = (trademark: TrademarkType | null) => {
		trademarkForm.logoUrl = '';
		trademarkForm.tmName = '';
		trademarkForm.id = undefined;
		trademarkForm.createTime = undefined;
		trademarkForm.updateTime = undefined;
		dialogVisible.value = true;
		if (trademark) {
			// 编辑
			dialogTitle.value = '编辑品牌';
			Object.assign(trademarkForm, trademark);
		} else {
			// 添加
			dialogTitle.value = '添加品牌';
		}
	};
	/**
	 * dialog提示框内进行提交新增、编辑品牌的操作
	 */
	let submitTrademark = async () => {
		let isValid = await formIns.value?.validate((valid) => {});
		if (!isValid) {
			ElMessage.error('请先填充相关数据');
			return;
		}
		let res: ResponseType<any>;
		// 根据是否具有id判断新增还是修改
		res = trademarkForm.id
			? await reqUpdateTrademark(trademarkForm)
			: await reqSaveTrademark(trademarkForm);
		if (res.code == 200) {
			ElMessage.success({
				message: trademarkForm.id ? '修改品牌成功' : '添加品牌成功',
			});
			dialogVisible.value = false;
			pageTrademark();
		} else {
			ElMessage.error({
				message: trademarkForm.id ? '修改品牌失败' : '添加品牌失败',
			});
		}
	};
	/**
	 * 根据id删除trademark
	 */
	let deleteTrademark = (id: number) => {
		ElMessageBox.confirm('确定要删除该品牌吗？', '警告', {
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(async () => {
			let { code, message, data } = await reqDeleteTrademark(id);
			if (code == 200) {
				ElMessage.success({ message: '删除成功' });
				pageTrademark();
			} else {
				ElMessage.error({ message: message });
			}
		});
	};

	/**
	 * 上传头像成功后的回调
	 * @param response
	 */
	let handleImgSuccess = (response: ResponseType<string>) => {
		if (response.code == 200) {
			ElMessage.success({
				message: '头像上传成功',
			});
			trademarkForm.logoUrl = response.data;
		} else {
			ElMessage.error({
				message: response.message,
			});
		}
	};
	// 文件上传前的回调，限制文件上传大小、格式
	let beforeImgUpload = (file: any): boolean => {
		console.log(file.type);
		if (!('image/jpeg' == file.type)) {
			ElMessage.error({ message: '文件只能是jpg格式' });
			return false;
		}
		if (file.size > 10 * 1024 * 1024) {
			ElMessage.error({ message: '文件大小不能超过10MB' });
			return false;
		}
		return true;
	};
	/**
	 * 页面记录条数改变的回调
	 */
	let pageSizeChange = () => {
		page.current = 1;
		pageTrademark();
	};
	onMounted(() => {
		pageTrademark();
	});
</script>
<style scoped lang="scss">
	.avatar-uploader {
		/* background-color: black; */
		border: 1px dotted black;
		box-sizing: border-box;
		padding: 1px;
		width: 178px;
		height: 178px;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: all 1s ease;
		overflow: hidden;
		font-size: 28px;
		&:hover {
			cursor: pointer;
			background-color: rgb(232, 220, 220);
			border-color: skyblue;
		}
		img {
			width: 178px;
			height: auto;
		}
	}
</style>
